<template>
  <div>
    <!-- 导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        class="addUserButton"
        @click="addRolesDialogVisible = true"
        >添加角色</el-button
      >
      <!-- 列表区 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <el-table-column type="expand" width="38">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcebter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcebter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  ><el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 渲染三级权限 -->
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesDialogClosed"
    >
      <el-form
        :model="addRolesForm"
        :rules="addRolesFormRules"
        ref="addRolesFormRef"
        label-width="70px"
      >
        <el-form-item label="名称" prop="roleName">
          <el-input
            placeholder="请输入角色名称"
            v-model="addRolesForm.roleName"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input
            type="textarea"
            placeholder="请输入角色描述"
            v-model="addRolesForm.roleDesc"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRoles">确认</el-button>
      </div>
    </el-dialog>

    <!-- 修改角色列表 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="editForm.roleName">
          </el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input
            type="textarea"
            placeholder="请输入角色描述"
            v-model="editForm.roleDesc"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editRolesInfo">确认</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        ref="treeRef"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        :props="treeProps"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      // 添加表单数据
      addRolesDialogVisible: false,
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加表单验证
      addRolesFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      // 修改表单数据
      editDialogVisible: false,
      editForm: {},
      // 修改表单验证
      editFormRules: {
        email: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      // 分配权限弹窗
      setRightDialogVisible: false,
      rightsList: [],
      defKeys: [],
      roleId: "",
      treeProps: {
        children: "children",
        label: "authName",
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error("获取权限列表失败失败！");
      }
      this.rolesList = res.data;
      //   console.log(this.rolesList);
    },
    // 添加用户角色页面的关闭事件,关闭后重置页面数据
    addRolesDialogClosed() {
      this.$refs.addRolesFormRef.resetFields();
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addRolesForm);
        if (res.meta.status !== 200) {
          this.$message.error("添加角色失败！");
        }
        this.$message.success("添加角色成功！");
      });
    },
    // 修改角色显示验证
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        this.$message.error("查询角色信息失败！");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 修改角色
    editRolesInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        );
        if (res.meta.status !== 200) {
          this.$message.error("角色修改失败！");
        }
        this.$message.success("角色修改成功！");
        this.editDialogVisible = false;
        this.getRolesList();
      });
    },
    // 删除角色
    async removeRolesById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmResult);
      // 确认返回 confirm ，取消返回 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消了删除！");
      }
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        this.$message.error("删除角色失败！");
      }
      this.$message.success("删除角色成功！");
      this.getRolesList();
    },
    // 删除角色指定菜单权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将删除该角色对应的操作权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消了删除！");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        this.$message.error("删除权限失败！");
      }
      this.$message.success("删除权限成功！");
      role.children = res.data;
    },
    // 展示分类权限
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        this.$message.error("获取权限失败！");
      }
      this.rightsList = res.data;
      // 递归获取3级权限
      this.getLeadKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 通过递归方式获取3级的权限
    getLeadKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeadKeys(item, arr));
    },
    // 分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 分配权限提交
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        this.$message.error("分配权限失败！");
      }
      this.$message.success("分配权限成功！");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcebter {
  display: flex;
  align-items: center;
}
</style>